{% from 'macros/icon.njk' import icon with context %}

{#
This renders the TOC for the current project_key. It looks at the current page
and marks it as active.
#}
{% macro navigationTreeSections() %}
{# toc defines the table of contents that appears to the left of the documentation. #}
{% set toc = docs[project_key].toc %}
{% set expandedSections = helpers.expandSections(toc, page.url, locale) %}
{{ navigationTreeSectionsInternal(expandedSections) }}
{% endmacro %}

{% macro navigationTreeSectionsInternal(expandedSections) %}
{% for item in expandedSections %}
  {% if item.sections %}
    <button class="navigation-tree__link button" data-expandable aria-expanded="{{ item.active }}">
      <div class="navigation-tree__icon">
        {{ icon('arrow-right', {hidden: true}) }}
      </div>
      <span>{{ item.title | i18n }}</span>
    </button>
    <div class="navigation-tree__nested">
      {{ navigationTreeSectionsInternal(item.sections) }}
    </div>
  {% elif item.url %}
    {#
      Check to see if the item is a regular post on the site or an external
      link. External links will display a special icon and open in a new
      window.
    #}
    {% set isExternal = helpers.isExternalLink(item.url) %}
    {% if isExternal %}
      {% set postTitle = item.title | i18n(locale) %}
      <a href="{{ item.url }}" class="navigation-tree__link" target="_blank" rel="noopener">
        <span class="display-inline-flex align-center">
          {{ postTitle }} {{ icon('external-link', {label: 'i18n.common.external_link' | i18n(locale), className: 'width-300 gap-left-100'}) }}
        </span>
      </a>
    {% else %}
      {% set post = helpers.findByUrl(collections.all, item.url, locale) %}
      {% if not post %}
        {#
          If we couldn't find a translated copy of the post, try to fallback to
          English so we at least have a link to something in our UI.
        #}
        {% set post = helpers.findByUrl(collections.all, item.url, 'en') %}
      {% endif %}

      {% if post %}
        <a href="{{ post.url }}" class="navigation-tree__link" {% if item.active %}{{ helpers.getLinkActiveState(post.url, page.url) | safe }}{% endif %}>
          <span>{{ post.data.title }}</span>
        </a>
      {% endif %}
    {% endif %}
  {% endif %}
{% endfor %}

{% endmacro %}
